const db=require('../dbConfig');

let getList=async(obj,userId)=>{
	let{note,page}=obj;
	let data={};
	let sql=`select website.id,url,short_url shortUrl,note,user.id userId,user.name username,user.avator,
	FROM_UNIXTIME(UNIX_TIMESTAMP(website.create_time), '%Y-%m-%d %H:%i:%s') create_time 
	from website,user 
	where website.user_id=user.id `;
	let arr=[userId];
	sql+=` and user_id=?`;
	sql+=` and  note like ? `; 
	if(page){
		page = (page - 1) *10;
		sql+=` order by  website.create_time desc limit ?,10`;
	}
	arr.push('%'+note+'%');arr.push(page);
	let result=await db(sql,arr);
	if(result.length==0){
		return {
		 	result:[],
		 	count:0
		}
	}
	else{
		data.result=result;
		let sql2='select count(*) count from website where',arr2=[userId];
		sql2+=` user_id=? and `;
		sql2+=` note like ? `; 
		arr2.push('%'+note+'%'); 
		data.count= await db(sql2,arr2);
		data.count=data.count[0].count;
		return data;
	}
}

let byCreate=(obj,userId)=>{
	let {id,url,shortUrl,note}=obj;
	let sql=`insert into website (id,user_id,url,short_url,note) values(?,?,?,?,?)`;
	return db(sql,[id,userId,url,shortUrl,note]);
}

let byUpdate=(obj,userId)=>{
	let {id,note}=obj;
	let sql=`update website set note=? where user_id=? and id=?`;
	return db(sql,[note,userId,id]);
}

let byDelete=(obj,userId)=>{
	let {id} = obj;
	id=id.join(',');
	let sql=`delete from website where FIND_IN_SET(id,?) and user_id=?`;
	return db(sql,[id,userId]);
}

module.exports={
	getList,byCreate,byUpdate,byDelete
}